/*
 * $Id: rwlock.c,v 1.3 2005-12-15 07:19:12 bacon Exp $
 */

#include <xp/bas/thr.h>
#include <xp/bas/rwl.h>
#include <xp/bas/time.h>
#include <xp/bas/stdio.h>

static xp_rwl_t rwl;

int dummy (xp_thr_t* thr)
{
	int i;

	for (i = 0; i < 25; i++) {
		xp_rwl_lockr (&rwl);
		xp_printf (XP_TEXT("dummy1-1. %d\n"), i);
		xp_sleep (10);
		xp_printf (XP_TEXT("dummy1-2. %d\n"), i);
		xp_sleep (10);
		xp_printf (XP_TEXT("dummy1-3. %d\n"), i);
		xp_sleep (10);
		xp_rwl_unlockr (&rwl);
		//xp_sleep (1000);
		xp_sleep (10);
	}

	return 0;
}

int dummy2 (xp_thr_t* thr)
{
	int i;

	for (i = 0; i < 25; i++) {
		xp_rwl_lockw (&rwl);
		xp_printf (XP_TEXT("dummy2-1. %i\n"), i);
		xp_sleep (10);
		xp_printf (XP_TEXT("dummy2-2. %i\n"), i);
		xp_sleep (10);
		xp_printf (XP_TEXT("dummy2-3. %i\n"), i);
		xp_sleep (10);
		xp_rwl_unlockw (&rwl);
		//xp_sleep (1000);
		xp_sleep (5);
	}

	return 0;
}

int xp_main ()
{
	xp_thr_t thr1, thr2, thr3, thr4;

	if (xp_rwl_open (&rwl) == XP_NULL) {
		xp_printf (XP_TEXT("cannot open rwlock\n"));
		return -1;
	}

	if (xp_thr_open (&thr1, dummy, 0) == XP_NULL ||
	    xp_thr_open (&thr2, dummy, 0) == XP_NULL ||
	    xp_thr_open (&thr3, dummy2, 0) == XP_NULL ||
	    xp_thr_open (&thr4, dummy2, 0) == XP_NULL) {
		xp_printf (XP_TEXT("cannot open threads\n"));
		return -1;
	}

	if (xp_thr_start (&thr1, 0) == -1 ||
	    xp_thr_start (&thr2, 0) == -1 ||
	    xp_thr_start (&thr3, 0) == -1 ||
	    xp_thr_start (&thr4, 0) == -1) {
		xp_printf (XP_TEXT("cannot start thread\n"));
		return -1;
	}

	xp_thr_join (&thr1);
	xp_thr_join (&thr2);
	xp_thr_join (&thr3);
	xp_thr_join (&thr4);

	xp_thr_close (&thr1);
	xp_thr_close (&thr2);
	xp_thr_close (&thr3);
	xp_thr_close (&thr4);

	xp_rwl_close (&rwl);

	return 0;
}
